const express = require('express')
const router = express.Router();

module.exports = router

const userRouter = require('./user')
const goodsRouter = require('./goods')
const cartRouter = require('./cart')

// 处理跨域
const whilelist = [
  'http://192.168.0.121:8080',
  'http://192.168.0.121:8081',
  'http://192.168.0.121:3000',

]
router.use(function(req,res,next){
    const origin = req.get('Origin');
    // 判断origin是否在白名单中（判断一个值是否存在数组中）
    if(whilelist.includes(origin)){
        res.set({
            'Access-Control-Allow-Origin':origin
        })

         // 处理复杂跨域中的预检请求
         if(req.method=="OPTIONS") {
            res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
            res.header("Access-Control-Allow-Methods","PUT,POST,GET,PATCH,DELETE,OPTIONS");
            res.sendStatus(200);/*让options请求快速返回*/
        } else{
            next();
        }
    }else{
        next();
    }
})

// 处理请求体数据
router.use(
    express.urlencoded({extended:false}), // querystring,qs：a=10&b=20 -> {a:10,b:20}
    express.json(),
)

// /api/user
router.use('/user',userRouter)
router.use('/goods',goodsRouter)
router.use('/cart',cartRouter)